package com.tbit.uqbike.webmanager.util.zfb;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.tbit.uqbike.object.pojo.ZfbPayConfig;
import com.tbit.uqbike.webmanager.util.LogUtil;
import com.tbit.uqbike.webmanager.util.redis.RedisUtil;
import com.tbit.uqbike.webmanager.util.spring.SpringUtils;
import com.tbit.uqbike.webmanager.util.zfb.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 支付宝退款
 *
 * @author Leon
 * 2017年11月9日 上午11:45:44
 */
@Slf4j
public class ZFBReturn {
    /**
     * 退款接口
     *
     * @param zfbPayConfig
     * @param
     * @return
     */
    @SuppressWarnings("deprecation")
    public static Boolean returnMoney(ZfbPayConfig zfbPayConfig, String out_trade_no, String out_refund_no, Double fee) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", zfbPayConfig.getPartner(), zfbPayConfig.getPriKey(), "json", AlipayConfig.input_charset, zfbPayConfig.getPubKey(), "RSA2");
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"refund_amount\":" + fee / 100 + "," + "\"refund_reason\":\"正常退款\"," + "\"out_request_no\":\"" + out_refund_no + "\","
                    + "\"operator_id\":\"OP001\"," + "\"store_id\":\"NJ_S_001\"," + "\"terminal_id\":\"NJ_T_001\"" + "  }");
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            LogUtil.info(response.getBody());
            if (response.isSuccess()) {
                return true;
            } else {
                LogUtil.warn(response.getErrorCode() + "," + response.getMsg());
                RedisUtil util = SpringUtils.getBean(RedisUtil.class);
                util.setEx(com.tbit.uqbike.webmanager.util.RedisUtil.getRefundHashId(out_trade_no), response.getMsg(), 5, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

}
